<?php

namespace Modules\DataCheck\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Modules\DataCheck\Enums\TaskSourceFileEnum;
use Modules\DataCheck\Excel\Import\SourceFileImport;
use Modules\DataCheck\Models\DcTaskSourceFile;
use Modules\DataCheck\Services\Import\SourceFileImportService;
use Throwable;

/**
 * 原始文件导入任务
 */
class SourceFileImportJob implements ShouldQueue
{
    use Queueable;

    public int $timeout = 300;

    /**
     * 最大尝试次数
     * @var int
     */
    public int $tries = 0;

    /**
     * Create a new job instance.
     */
    public function __construct(private readonly DcTaskSourceFile $fileModel)
    {
    }

    /**
     * Execute the job.
     */
    public function handle(SourceFileImport $import): void
    {
        try {
            $import->handle($this->fileModel);
        } catch (\Throwable $throwable) {
            $this->failed($throwable);
        }
    }

    /**
     * 处理失败作业
     * @param Throwable|null $throwable
     * @return void
     */
    public function failed(?Throwable $throwable): void
    {
        if (empty($throwable)) {
            return;
        }

        $error = [
            'msg' => '原表excel文件解析异常',
            'params' => [
                'file_id' => $this->fileModel->id,
                'file_path' => $this->fileModel->file_path,
            ],
            'error' => [
                'msg' => $throwable->getMessage(),
                'file' => $throwable->getFile(),
                'line' => $throwable->getLine(),
            ],
        ];

        $this->fileModel->update([
            'file_state' => TaskSourceFileEnum::FAILED->value,
            'remark' => json_encode($error, JSON_UNESCAPED_UNICODE),
        ]);
    }
}
